package com.qkl.upload.publics.utils;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

public class DirectoryFinder {

    public static void main(String[] args) throws IOException {
        // 起始路径
        Path startingDir = Paths.get("C:/");

        // 要搜索的模式，例如所有目录名以"t"开头的
        String glob = "glob:**/t*/";

        // 查找匹配的目录
        List<Path> matchedDirectories = findDirectories(startingDir, glob);

        // 输出结果
        for (Path path : matchedDirectories) {
            System.out.println(path);
        }
    }

    public static List<Path> findDirectories(Path startingDir, String glob) throws IOException {
        final List<Path> matchedDirectories = new ArrayList<>();
        PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher(glob);

        Files.walkFileTree(startingDir, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (pathMatcher.matches(dir)) {
                    matchedDirectories.add(dir);
                }
                return FileVisitResult.CONTINUE;
            }
        });

        return matchedDirectories;
    }
}
